// pages/device/writesetting/writesetting.js
// 设备参数

var app = getApp()
var cmd = require('../../../command/command.js')
var bluetooth = require('../../../command/bluetooth.js')

var extendCmd = [
  ["start", "定时启", true, " : : ", ""],
  ["stop", "定时停", true, " : : ", ""],
  ["sleep", "进入休眠时间", true, " : : ", ""],
]

var writeCommand = [
  ["000A", "输出电压", true, 20, "V", 20, 30],
  ["000B", "充电电流", true, 10, "A", 10, 65],
  ["000C", "自启电压", true, 20, "V", 20, 28],
  ["000D", "熄火电流", true, 5, "A",  5, 30],
  ["000E", "熄火电压", true, 20, "V", 20, 40],
  ["001A", "工作模式", false, 2, "标准"],
  // ["000F", "时间（时）", null, 0, 500, "时"],
  // ["0010", "时间（分）", null, 0, 60, "分"],
  ["extend", "高级", true],
  ["start", "定时启", true, "00:00", "", false],
  ["stop", "定时停", true, "00:00", "", false],
  ["sleep", "进入休眠时间", true, "00:00", "", false],
  ["0021", "稳定性调节", false, 1, "中"],
  ["0020", "加浓控制", true, 40, "%", 0, 100],
  // "0011": ["电流低或电压高停机时间（秒）", null, 0, 60000],
  // "0012": ["比列调节", null, 0, 100],
  // "0013": ["积分调节", null, 0, 100],
  // "0014": ["微分调节", null, 0, 100],
  // "0015": ["电压校正", null, 0, 100],
  // "0016": ["电流校正", null, 0, 100],
  // "0017": ["采样时间", null, 0, 100],
]

//判断发送的命令有没有返回成功，mcu收到命令会放回响应
var checkIsCheck = {};

Page({

  /**
   * 页面的初始数据
   */

  data: {
    dialogTitle: "",
    objectArray: writeCommand,
    showModal: false,
    workmode: null,
    desc:"",
    inputData: "",
    key : null,
    modelists:[{ label: '节能', value: 1 },
    { label: '标准', value: 2 },
    { label: '充电', value: 3 },
    { label: '自定义', value: 4 }
    ],
    statelists:[{ label: '低', value: 1 },
    { label: '中', value: 2 },
    { label: '高', value: 3 }],

    pickerlists:[],
    
    timerRecValue: null,
    isTimerSetting: false, //正在设置定时器
    value: 'label_2',
    // 下拉框
    list: [{
      value: 'label_1',
      label: '设备状态',
      icon: 'pin'
    },
    {
      value: 'label_2',
      label: '设备参数',
      icon: 'app'
    },
    {
      value: 'label_3',
      label: '参数页面',
      icon: 'chat'
    },
  ],
  },

  sendTimeOutId : -1,

  initParamInfo(){
    
  },
  showInfo(event) {
    const key = event.target.dataset.id
    console.log(key)
    var tableInfo = app.getCmdDescTable()
    if(tableInfo == null){
        return
    }
    console.log(tableInfo)
    var desc = ""
    tableInfo.forEach(element => {
        console.log(element.name, element.desc)
        if(element.name == key){
            desc = element.desc
        }
    });
    wx.showModal({
        title: '',
        content: desc,
        showCancel: false,
    })
    
  },

  goMachineState() {
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: "../home/home",
          })
          
        }
        else{
          wx.navigateTo({
            url: "../home/home",
          })
        }

    // this.isAutoSend = true
    console.log('set---over')
  },
  /**
   * 设置参数页面
   */
  goSetMachine() {
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: "../writesetting/writesetting",
          })
          
        }
        else{
          wx.navigateTo({
            url: "../writesetting/writesetting",
          })
        }
    console.log("set over")
  },
  /**
   * 参数页面
   */
  goMachineSetting() {
        console.log("current-Page-Length:",getCurrentPages().length)

        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: "../state/state",
          })
          
        }
        else{
          wx.navigateTo({
            url: "../state/state",
          })
        }
  },
  onChange(e) {
    this.setData({
      value: e.detail.value,
    });
        console.log("current-Page-Length:",getCurrentPages().length)

    if (e.detail.value == "label_1") {
      if(getCurrentPages().length > 8)
      {
        wx.reLaunch({
          url: "../home/home",
        })
        
      }
      else{
        wx.navigateTo({
          url: "../home/home",
        })
      }
    } else if (e.detail.value == "label_2") {
      // wx.navigateTo({
      //   url: "../writesetting/writesetting",
      // })
    } else {
        console.log("切换state")
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: "../state/state",
          })
          
        }
        else{
          wx.navigateTo({
            url: "../state/state",
          })
        }

        console.log("切换成功...")
    }
    // setTimeout(()=>{
    //   // this.setData({
    //   //   value: "label_2",
    //   // })
    // }, 1000);
  },

  valueInput(event) {
    console.log(event.detail.value)
    this.data.inputData = event.detail.value
  },

  /**
   * 弹出窗口，设置数据
   * @param {*} event 
   */
  goSetValue(event){
    
      // 短时间内多次重复设置的情况下，只启用一个
      if(this.sendTimeOutId != -1){
        console.log("正在设置上一个的参数值")
        return
      }

    var title, _inputVale, _desc; //这几个参数用来显示的

    const key = event.target.dataset.item
    if(key){
      var mode = 0
      this.data.key = key //将数据保存在data.key中
      switch(key[0]){
        case "000A": title = "输出电压"
        _inputVale = key[3]
        _desc = key[5] + "V-" + key[6] + "V"
          break;
        case "000B": title = "充电电流"
        _inputVale = key[3]
        _desc = key[5] + "A-" + key[6] + "A"
          break;
        case "000C": title = "自启电压"
        _inputVale = key[3]
        _desc = key[5] + "V-" + key[6] + "V"
        break;
        case "000D": title = "熄火电流"
        _inputVale = key[3]
        _desc = key[5] + "A-" + key[6] + "A"
        break;
        case "000E": title = "熄火电压"
        _inputVale = key[3]
        _desc = key[5] + "V-" + key[6] + "V"
        break;
        case "001A": title = "工作模式"
        mode = 1
        this.setData({
          pickerlists : this.data.modelists
        })
        break;
        case "start": title = "定时启"
        mode = 2
        break;
        case "stop": title = "定时停"
        mode = 2
        break;
        case "sleep": title = "进入休眠时间"
        mode = 2
        break;
        case "0021": title = "稳定性调节"
        mode = 1
        this.setData({
          pickerlists : this.data.statelists
        })
        break;
        case "0020": title = "加浓控制"
        _inputVale = key[3]
        _desc = key[5] + "-" + key[6] + ""
        break;
      }

      switch(mode){
        case 0: //输入框
          this.setData({
            desc : _desc,
            inputData : _inputVale,
          })
          break;
        case 1: //选择框
          break; 
        case 2: //时间框
          break;
      }
      this.setData({
        dialogTitle : title,
        showModal : true,
        workmode : mode,
      })
    }
  },

  /**
   * 取消
   * @param {*} event 
   */
  onCancel(event){
    this.setData({
      showModal : false
    })
  },
  /**
   * 确认修改值
   * @param {*} event 
   */
  onConfirm(event){
    console.log(event)
    const key = this.data.key
    // console.log(this.data.key)
    var checkRange = function(){
      if(key[3]<key[5] || key[3]>key[6]){
        wx.showToast({
          title: '数值范围错误',
          icon: "error"
        })
        return false
      }
      return true
    }

    if(key){
      this.data.key = key
      switch(key[0]){
        case "000A":
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[0][3]": key[3]
          })
        break;
        case "000B":
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[1][3]": key[3]
          })
        break;
        case "000C":
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[2][3]": key[3]
          })
        break;
        case "000D":
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[3][3]": key[3]
          })
        break;
        case "000E":
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[4][3]": key[3]
          })
        break;
        case "0020": //"加浓控制"
          key[3] = parseFloat(this.data.inputData)
          if(!checkRange()){
            return
          }
          this.setData({
            "objectArray[11][3]": key[3]
          })
        break;
        case "001A": //工作模式
          key[3] = event.detail.value[0]
          key[4] = event.detail.label[0]
          this.setData({
            "objectArray[5][3]": key[3],
            "objectArray[5][4]": key[4]
          })
        break;
        case "start": //title = "定时启"
        key[3] = event.detail.value
          this.setData({
            "objectArray[7][3]": key[3]
          })
        break;
        case "stop": //title = "定时停"
        key[3] = event.detail.value
        this.setData({
          "objectArray[8][3]": key[3]
        })
        break;
        case "sleep": //title = "进入休眠时间"
        key[3] = event.detail.value
        this.setData({
          "objectArray[9][3]": key[3]
        })
        break;
        case "0021": //title = "稳定性调节"
          key[3] = event.detail.value[0]
          key[4] = event.detail.label[0]
          this.setData({
            "objectArray[10][3]": key[3],
            "objectArray[10][4]": key[4]
          })
        break;
      }
    }

    this.setData({
      showModal : false,
    })

    writeCommand = this.data.objectArray

    console.log(key[0], key[3])
    this.goSend2(key[0], key[3])
  },

  sendTime(hourCode, minCode, timeString){
    if(timeString === "00:00"){
      return
    }

    if(this.sendTimeOutId != -1){
      console.log("正在设置上一个的参数值")
      return
    }

    checkIsCheck[hourCode] = true
    checkIsCheck[minCode] = true
    const [hours, minutes] = timeString.split(':').map(Number);
    bluetooth.send(cmd.getWriteCommand(hourCode, hours))
    bluetooth.send(cmd.getWriteCommand(minCode, minutes))

    const TimerFunc = (key1, key2) => {
      // console.log(key)
      this.sendTimeOutId = -1
      if(checkIsCheck[key1] || checkIsCheck[key2]){
        wx.showToast({
          title: '设置超时失败',
          icon: "error",
        })
      }else{
        wx.showToast({
          title: '设置成功',
          icon: "success",
        })
      }
    }

    console.log('======>', 1000, hourCode, minCode)
    this.sendTimeOutId = setTimeout(TimerFunc, 1000, hourCode, minCode)
  },
  /**
   * 设置按钮，点击发送配置的数据
   * @param {*} event 
   */
  goSend(event) {
    console.log("test: ", event.target.dataset.item)

    const dataset = event.target.dataset.item
  
    // goSend2(dataset[0], dataset[3])
  },

  goSend2(key, value) {
    if(key === "start"){ //定时启 时间
      this.sendTime("001E", "001F", value)
    }else if(key === "stop"){ //定时停时间
      this.sendTime("000F", "0010", value)
    }else if(key === "sleep"){ //进入休眠时间
      this.sendTime("0022", "0023",  value)
    }else{
      console.log(key,value)
      if (null === value || "" === value) {
        console.log("请输入值")
        return
      }

      var checkCode = key // 命令码
      // 判断checkIsCheck[checkCode]有没有变化来判断是否接收到放回值
      checkIsCheck[checkCode] = true
      var str = (cmd.getWriteCommand(checkCode, value))
      bluetooth.send(str)
      this.sendTimeOutId = setTimeout((parmkey = checkCode) => {
        // console.log(key)
        console.log(parmkey, checkIsCheck[parmkey])
        this.sendTimeOutId = -1
        if(checkIsCheck[parmkey]){
          wx.showToast({
            title: '设置超时失败',
            icon: "error",
          })
        }else{
          wx.showToast({
            title: '设置成功',
            icon: "success",
          })
        }
      }, 1000)
    }
  },
  handleChange(e) {

    const keyCode = e.target.dataset.item[0]
    const _value = e.detail.value

    //检查时间是否为零
    var isError = false
    switch(keyCode){
      case "start": 
      if(this.data.objectArray[7][3] == "00:00"){
        isError = true
      }
      break
      case "stop" : 
      if(this.data.objectArray[8][3] == "00:00"){
        isError = true
      }
      break
      case "sleep": 
      if(this.data.objectArray[9][3] == "00:00"){
        isError = true
      }
      break
    }

    if(isError == true){
      wx.showToast({
        title: '时间不能为零',
        icon: "error",
      })
      return
    }
    
    console.log("handleChange", e.target.dataset.item[0], e.detail.value)

    switch(keyCode){
      case "start": 
      writeCommand[7][5] = _value
      break
      case "stop" : 
      writeCommand[8][5] = _value
      break
      case "sleep": 
      writeCommand[9][5] = _value
      break
    }

    var restoreSwitchButton = (keyCode)=>{
      switch(keyCode){
        case "start": 
        writeCommand[7][5] = !writeCommand[7][5]
        break
        case "stop" : 
        writeCommand[8][5] = !writeCommand[8][5]
        break
        case "sleep": 
        writeCommand[9][5] = !writeCommand[9][5]
        break
      }
    }

    this.setData({
      defaultVal: e.detail.value,
      objectArray: writeCommand
    });
    
    this.data.timerRecValue = null
    checkIsCheck["0024"] = true

    this.goSendTimerCode(e.target.dataset.item[0], e.detail.value)

    setTimeout((code = keyCode) => {
      if(checkIsCheck["0024"] || this.data.timerRecValue == null){
        wx.showToast({
          title: '设置超时失败',
          icon: "error",
        })
        restoreSwitchButton(code)
      } else{
        wx.showToast({
            title: '设置成功',
            icon: "success",
        })
        var state = this.data.timerRecValue
        writeCommand[7][5] = Boolean(state & 0x0002)  //定时启在工作
        writeCommand[8][5] = Boolean(state & 0x0001) //定时停在工作
        writeCommand[9][5] = Boolean(state & 0x0004) //休眠在工作 
      }
      this.setData({
        defaultVal: e.detail.value,
        objectArray: writeCommand
      });
    }, 1000)
  },
  /**
   * 启动定时启
   */
  goSendTimerCode(type, isenable){
    var value;
    if(type === "stop"){ //定时停 时间
      value = "01"
      if(isenable){
        value += "01"
      } else{
        value += "00"
      }
    }else if(type === "start"){ //定时启时间
      value = "02"
      if(isenable){
        value += "02"
      } else{
        value += "00"
      }
    }else if(type === "sleep"){ //进入休眠时间
      value = "04"
      if(isenable){
        value += "04"
      } else{
        value += "00"
      }
    }else{
      return
    }
    bluetooth.send(cmd.getWriteCommand("0024", value))
  },
  /**
   * 判断是否是当前页面，因为切换页面时，timer没有关闭，判断一下
   * 原因：在onLoad加载的定时器，退出页面在调用onUnload，但往前切换页面并不会
   * 而，在onShow情况下加载定时器, onshow和onhide的场景有点多
   * 
   * 因此不研究其中差别了，直接判断是否在当前页面，再发送数据即可
   */
  isCurPage(){
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    return currentPage.route === 'pages/device/writesetting/writesetting';    
  },

  /**
   * 刷新界面
   */
  updata(){
    if(!this.isCurPage()){
      return
    }
    if(!app.globalData.connected){
      return
    }

    var stopH = null, stopM = null, startH = null, startM = null, sleepH = null, sleepM = null;
    var needFresh = false
    var timerRecValue = null
    var recData = Object.keys(cmd.recDataStruct)
    for (let index = 0; index < recData.length; index++) {
      const e = recData[index];
      if( cmd.recDataStruct[e][1] == true ){
        needFresh = true
        cmd.recDataStruct[e][1] = false
        checkIsCheck[e] = false
        var value = cmd.recDataStruct[e][0]
        console.log(e, cmd.recDataStruct[e][0], cmd.recDataStruct[e][1], checkIsCheck[e])
        
        switch(e){
          case "000A": writeCommand[0][3] = value //输出电压
          break
          case "000B": writeCommand[1][3] = value //充电电流
          break
          case "000C": writeCommand[2][3] = value //自启电压
          break
          case "000D": writeCommand[3][3] = value //熄火电流
          break
          case "000E": writeCommand[4][3] = value //熄火电压
          break
          case "001A": //模式控制
            writeCommand[5][3] = value
          break
          case "0020": //加浓控制
          writeCommand[11][3] = value
          break
          case "0021": //稳定性调节
          writeCommand[10][3] = value
          break
          case "001E": //启时
          startH = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "001F": //启分
          startM = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "000F": //停时
          stopH = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "0010": //停分
          stopM = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "0022": //休眠时
          sleepH = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "0023": //休眠分
          sleepM = value != null ? value.toString().padStart(2, '0') : null;
          break
          case "0024": //时间启动停止位
          timerRecValue = value
          break
        }
      }
    }

    if(startH != null && startM != null)
        writeCommand[7][3] = startH + ":" + startM
    if(stopH != null && stopM != null)
        writeCommand[8][3] = stopH + ":" + stopM
    if(sleepH != null && sleepM != null)
        writeCommand[9][3] = sleepH + ":" + sleepM

    if(timerRecValue != null){
        this.data.timerRecValue = timerRecValue
        var state = this.data.timerRecValue
        writeCommand[7][5] = Boolean(state & 0x0002)  //定时启在工作
        writeCommand[8][5] = Boolean(state & 0x0001) //定时停在工作
        writeCommand[9][5] = Boolean(state & 0x0004) //休眠在工作 
    }
    
    if(needFresh == true){
      this.setData({
        objectArray : writeCommand,
      })
    }
  },

  updataId : null,
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("设备参数OnShow----")
    // 先发一遍指令刷新
    if(app.globalData.connected){
      var comandArray = ["controllerOutVoltageR", 
      "chargeCurrentR",
      "autoStartVoltageR",
      "autoStopCurrentR",
      "autoStopVoltageR",
      "machineMode",
      "adjust",
      "plusContral",
      "startTimeHour",
      "startTimeMin",
      "sleepTimeHour",
      "sleepTimeMin",
      "stopTimeHour",
      "stopTimeMin",]
      for(var i = 0; i < comandArray.length; i++){
        bluetooth.send(cmd.getCommandByName(comandArray[i]))
      }
    }
    this.setData({
      value: 'label_2',
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.updataId)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initParamInfo()

    if(this.updataId == null)
        this.updataId = setInterval(() => { this.updata() }, 50);
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.updataId)
    this.updataId = null
  },
})